//
//  CodeController.swift
//  用户二维码
//
//  Created by smile on 2019/7/18.
//  Copyright © 2019 ixuea. All rights reserved.
//

import UIKit

class CodeController: BaseTitleController {
    
    /// 内容容器
    @IBOutlet weak var contentContainer: UIView!
    
    /// 用户头像
    @IBOutlet weak var ivAvatar: UIImageView!
    
    /// 昵称
    @IBOutlet weak var lbNickname: UILabel!
    
    
    /// 显示二维码的控件
    @IBOutlet weak var ivCode: UIImageView!
    
    /// 用户Id
    var userId:String!
    
    override func initViews() {
        super.initViews()
        
        setTitle("用户二维码")
        
        ViewUtil.showSmallRadius(contentContainer)
        
        //头像圆角
        ViewUtil.showRadius(ivAvatar, 30)
    }
    
    override func initDatas() {
        super.initDatas()
        
        Api.shared.userDetail(id: userId).subscribeOnSuccess { (data) in
            if let data=data?.data{
                self.showData(data)
            }
        }.disposed(by: disposeBag)
    }
    
    func showData(_ data:User) {
        //显示头像
        ImageUtil.showAvatar(ivAvatar, data.avatar)
        
        //昵称
        lbNickname.text=data.nickname
        
        //我们这里的二维码的数据
        //就是一个网址
        //真实的数据在网址的查询参数里面
        //http://dev-my-cloud-music-api-rails.ixuea.com/v1/monitors/version?u=
        let qrCodeData="\(QRCODE_URL)\(data.id!)"
        
        //生成二维码
        showCode(qrCodeData)
    }
    
    /// 生成二维码
    ///
    /// - Parameter data: <#data description#>
    func showCode(_ data:String) {
        //根据数据创建一个二维码Image
        let qrImage=LBXScanWrapper.createCode(codeType: "CIQRCodeGenerator", codeString: data, size: ivCode.bounds.size, qrColor: UIColor.black, bkColor: UIColor.white)
        
        //获取应用图标
        let logoImage = UIImage(named: "AppIcon")
        
        //把应用图标嵌入到二维码中
        ivCode.image = LBXScanWrapper.addImageLogo(srcImg: qrImage!, logoImg: logoImage!, logoSize: CGSize(width: 15, height: 15))
    }
   
    /// 视图即将可见
    ///
    /// - Parameter animated: <#animated description#>
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        //把标题栏设置为亮色
        setTitleBarLight()
    }
    
    /// 视图即将消失
    ///
    /// - Parameter animated: <#animated description#>
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        //把标题栏设置为默认
        setTitleBarDefault()
    }
}

// MARK: - 启动方法
extension CodeController{
    
    /// 启动方法
    ///
    /// - Parameters:
    ///   - nav: <#nav description#>
    ///   - userId: <#userId description#>
    static func start(_ nav:UINavigationController,_ userId:String) {
        //创建控制器
        let controller=nav.storyboard!.instantiateViewController(withIdentifier: "Code") as! CodeController
        
        //传递参数
        controller.userId=userId
        
        //将控制器添加到导航器中
        nav.pushViewController(controller, animated: true)
    }
}
